package com.imooc.spark.project.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * HBase 工具类,用单例模式封闭
 */

public class HBaseUtils {

    HBaseAdmin admin= null;

    Configuration configuration = null;

    private HBaseUtils(){


        configuration = new Configuration();

        configuration.set("hbase.zookeeper.quorum","localhost:2181");
        configuration.set("hbase.rootdir","hdfs://localhost:8020");


      try {

          admin = new HBaseAdmin(configuration);

      } catch (Exception e){

          e.printStackTrace();
      }

    }

    private static HBaseUtils INSTANCE = null;

    public static synchronized HBaseUtils getINSTANCE(){

        if(INSTANCE == null){

            INSTANCE = new HBaseUtils();
        }

        return INSTANCE;
    }


    /**
     * get the HBase TABLE 的实例
     * @return
     */


 public HTable getTable(String tableName){

     HTable table = null;

     try {
         table = new HTable(configuration,tableName);
     }  catch (Exception e){
         e.printStackTrace();
     }

     return table;
 }

    /**
     *
     * @param tableName HBase 表名
     * @param rowKey   HBase 表名的rowKey
     * @param cf        HBase 的columnfamily
     * @param column    HBASE  的列
     * @param value     写入HBASE的value
     */
 public void put(String tableName,String rowKey,String cf, String column,String value){

     HTable table = getTable(tableName);

     Put put = new Put(Bytes.toBytes(rowKey));

     put.add(Bytes.toBytes(cf),Bytes.toBytes(column),Bytes.toBytes(value));

     try {

         table.put(put);

     } catch (Exception e){

         e.printStackTrace();
     }




 }



    public static void main(String[] args) {

        HTable table = HBaseUtils.getINSTANCE().getTable("imooc_course_clickout");

        System.out.println(table);

        String tableName = "imooc_course_clickout";

        String rowkey = "20190303_88";

        String cf = "info";

        String column = "click_count";

        String value = "2";

        HBaseUtils.getINSTANCE().put(tableName,rowkey,cf,column,value);

    }



}
